<template>
  <div class="app-container">
    <!-- 订单管理 -->
    <div class="search-bar">
      <!-- 订单搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="订单编号" prop="code">
          <el-input
            v-noSpace
            v-model="queryParams.code"
            placeholder="请输入订单编号"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="客户编号" prop="companyCode">
          <el-input
            v-noSpace
            class="!w-[192px]"
            v-model="queryParams.companyCode"
            placeholder="请输入客户编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="合同编号" prop="contractCode">
          <el-input
            v-noSpace
            v-model="queryParams.contractCode"
            class="!w-[192px]"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="业务员" prop="salesMan">
          <!-- <el-input v-noSpace v-model="queryParams.salesMan" placeholder="请输入销售人员" clearable @keyup.enter="handleQuery"
                 /> -->

          <el-select
            v-model="queryParams.salesMan"
            placeholder="请选择业务员"
            clearable
            filterable
            class="!w-[192px]"
            @change="handleQuery"
          >
            <el-option
              v-for="item in optionsSalesMan"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[192px]"
            @change="handleQuery"
          >
            <!-- <el-option label="未提交" :value="'0'" /> -->
            <el-option label="待审核" :value="'0'" />
            <el-option label="审核拒绝" :value="'1'" />
            <el-option label="已审核" :value="'2'" />
            <el-option label="计划完成" :value="'3'" />
            <el-option label="生产完成" :value="'4'" />
            <el-option label="交付完成" :value="'5'" />
            <el-option label="已退货" :value="'6'" />

            <!-- <el-option label="取消订单" :value="'7'" />
                <el-option label="取消待审核" :value="'8'" /> -->
          </el-select>
        </el-form-item>

        <el-form-item label="创建日期" prop="timeScopes">
          <el-date-picker
            v-model="queryParams.timeScopes"
            type="datetimerange"
            placeholder="选择创建日期"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            picker-options="pickerOptions"
            clearable
            @change="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button
            v-hasPerm="'sys:master:edit'"
            type="warning"
            icon="menu"
            @click="handleOpenDialog({}, 'add')"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 订单列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" show-overflow-tooltip>
        <el-table-column prop="code" label="订单编号" width="250" align="center" />
        <el-table-column prop="docType" label="订单类型" align="center" width="120">
          <template #default="scope">
            <span>
              {{ getDocTypeLabel(scope.row.docType) }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="companyCode" label="客户编号" align="center" width="110" /> -->
        <el-table-column prop="customerName" label="客户名称" width="110" align="center">
          <template #default="scope">
            {{ `${scope.row.customerName}-${scope.row.companyCode}` }}
          </template>
        </el-table-column>
        <el-table-column prop="contractCode" label="归属合同" align="center" width="110" />
        <el-table-column prop="salesMan" label="业务员" align="center" width="110">
          <template #default="scope">
            {{
              optionsSalesMan.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" align="center" width="110" />
        <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
        <el-table-column prop="orderAmount" label="总金额" width="150" align="center" />
        <el-table-column prop="discountAmount" label="折后金额" width="150" align="center" />
        <el-table-column prop="deliveryDate" label="送货日期" width="150" align="center" />
        <el-table-column prop="status" label="状态" align="center" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="warning">待审核</el-tag>
            <el-tag v-if="scope.row.status == 1" type="danger">审核拒绝</el-tag>
            <el-tag v-if="scope.row.status == 2" type="success">已审核</el-tag>
            <el-tag v-if="scope.row.status == 3" type="success">计划完成</el-tag>
            <el-tag v-if="scope.row.status == 4" type="success">生产完成</el-tag>
            <el-tag v-if="scope.row.status == 5" type="success">交付完成</el-tag>
            <el-tag v-if="scope.row.status == 6" type="danger">已退货</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
        <el-table-column
          prop="approvalComment"
          label="审核意见"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row, 'view')"
            >
              查看
            </el-button>
            <el-button
              v-if="
                scope.row.status != 2 &&
                scope.row.status != 3 &&
                scope.row.status != 4 &&
                scope.row.status != 5 &&
                scope.row.status != 6
              "
              type="primary"
              link
              size="small"
              @click="handleApproved(scope.row)"
              v-hasPerm="'sys:master:app'"
            >
              审核
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              v-if="
                scope.row.status == 2 ||
                scope.row.status == 3 ||
                scope.row.status == 4 ||
                scope.row.status == 5
              "
              v-hasPerm="'sys:master:return'"
              @click="handleReturn(scope.row)"
            >
              退货
            </el-button>
            <el-button
              v-hasPerm="'sys:master:edit'"
              v-if="scope.row.status == 0 || scope.row.status == 1"
              type="primary"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'edit')"
            >
              修改
            </el-button>

            <!-- <el-button
                  v-if="
                    scope.row.status != 0 &&
                    scope.row.status != 1 &&
                    scope.row.status != 2 &&
                    scope.row.status != 6
                  "
                  type="primary"
                  link
                  size="small"
                  @click="handleCanle(scope.row)"
                >
                  取消订单
                </el-button> -->

            <el-button
              v-hasPerm="'sys:master:del'"
              v-if="
                scope.row.status != 2 &&
                scope.row.status != 3 &&
                scope.row.status != 4 &&
                scope.row.status != 5 &&
                scope.row.status != 6
              "
              type="danger"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'del')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormDataRef"
        :model="dialogFormData"
        :rules="rules"
        label-width="120px"
        :disabled="formDisabled"
      >
        <el-row>
          <el-col v-if="dialog.title != '新增'" :span="12">
            <el-form-item label="订单编号" prop="code">
              <el-input
                v-noSpace
                v-model="dialogFormData.code"
                placeholder="请输入订单编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单类型" prop="docType">
              <el-select
                v-model="dialogFormData.docType"
                placeholder="请选择订单类型"
                :disabled="dialog.title != '新增'"
              >
                <el-option
                  v-for="item in docTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <!-- <el-input v-noSpace v-model="dialogFormData.customerName" placeholder="请输入客户名称" /> -->
              <el-select
                v-model="dialogFormData.customerName"
                placeholder="请选择客户名称"
                clearable
                filterable
                @change="changeName"
                @visible-change="getName"
              >
                <el-option
                  v-for="item in optionsName"
                  :key="item.value"
                  :label="item.label + item.value"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="companyCode">
              <el-input
                v-noSpace
                v-model="dialogFormData.companyCode"
                placeholder="请输入客户编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-select
                v-model="dialogFormData.contactPerson"
                placeholder="请选择联系人"
                clearable
                @change="changeContactPerson"
              >
                <el-option
                  v-for="item in optionsContact"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value.toString()"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="contactPhone">
              <el-input
                v-noSpace
                v-model="dialogFormData.contactPhone"
                placeholder="请输入联系人电话"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属合同" prop="contractCode">
              <el-input
                v-noSpace
                v-model="dialogFormData.contractCode"
                placeholder="请输入归属合同"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="送货日期" prop="deliveryDate">
              <el-date-picker
                v-model="dialogFormData.deliveryDate"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员" prop="salesMan">
              <!-- <el-input v-noSpace v-model="dialogFormData.salesMan" placeholder="请输入业务员" /> -->

              <el-select
                v-model="dialogFormData.salesMan"
                placeholder="请选择业务员"
                clearable
                filterable
              >
                <el-option
                  v-for="item in optionsSalesMan"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value.toString()"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="送货地址" prop="address">
              <!-- <el-input v-noSpace
                v-model="dialogFormData.address"
                :rows="2"
                type="textarea"
                placeholder="请输入审核意见"
                disabled
              /> -->
              <el-select
                v-model="dialogFormData.address"
                placeholder="请选择客户地址"
                clearable
                filterable
                @visible-change="getAddressList"
              >
                <el-option
                  v-for="item in optionsAddress"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="dialogFormData.remark"
                :rows="2"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="审核意见" prop="approvalComment">
              <el-input v-noSpace
                v-model="dialogFormData.approvalComment"
                :rows="2"
                type="textarea"
                placeholder="请输入审核意见"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>

      <el-divider />

      <el-form
        ref="dialogFormDataProRef"
        :model="dialogFormDataPro"
        :rules="rulesPro"
        label-width="120px"
        v-if="!formDisabled && dialog.title != '修改'"
      >
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-input v-noSpace
                v-model="dialogFormDataPro.productType"
                placeholder="请输入产品类型"
                disabled
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input
                v-noSpace
                v-model="dialogFormDataPro.productCode"
                placeholder="请输入产品编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-select
                v-model="dialogFormDataPro.productName"
                placeholder="请选择产品名称"
                clearable
                filterable
                @change="changeProduct"
                @visible-change="getContractList"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`数量（${unitValue?.label || ''}）`" prop="qty">
              <el-input-number v-model="dialogFormDataPro.qty" placeholder="请输入数量" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number v-model="dialogFormDataPro.unitPrice" placeholder="请输入单价" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="dialogFormDataPro.remark"
                :rows="2"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" />
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSavePro('continue')">添加产品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table v-loading="loading" :data="rowTableData">
        <!-- <el-table-column label="产品类型" align="center" prop="productType" />
        <el-table-column label="产品编号" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="单价" align="center" prop="unitPrice" />
        <el-table-column label="数量（kg）" align="center" prop="qty" /> -->

        <el-table-column prop="productCode" label="产品编号" align="center" />
        <el-table-column prop="productName" label="产品名称" align="center" />
        <!-- 修改 qty 和 price 列 -->
        <el-table-column label="每份数量" prop="qty" align="center" width="200">
          <template #default="scope">
            <div class="flex-center" v-if="!formDisabled && dialog.title !== '修改'">
              <el-input v-noSpace class="flex-1" v-model="scope.row.qty" />
              <div>{{ unitFormat(scope.row.unit) }}</div>
            </div>
            <div v-else class="flex-center">
              {{ scope.row.qty + unitFormat(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价(元)" prop="unitPrice" align="center" width="200">
          <template #default="scope">
            <div v-if="!formDisabled && dialog.title !== '修改'">
              <el-input v-noSpace v-model="scope.row.unitPrice" />
            </div>
            <div v-else>{{ scope.row.unitPrice }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="rowRemark" label="备注" show-overflow-tooltip align="center" />

        <el-table-column
          label="操作"
          fixed="right"
          width="70"
          align="center"
          v-if="!formDisabled && dialog.title !== '修改'"
        >
          <template #default="scope">
            <el-button
              v-if="dialog.title == '新增' || dialog.title == '修改'"
              type="danger"
              size="small"
              link
              @click="delRow(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer v-if="!formDisabled">
        <div v-if="buttonIsishow" class="dialog-footer flex-center">
          <el-button @click="handleCloseDialog">取 消</el-button>
          <!-- <el-button type="primary" @click="handleSubmit('save')">暂 存</el-button> -->
          <el-button
            v-if="dialog.title == '新增' || dialog.title == '修改'"
            v-debounce="handleSubmit"
            type="primary"
          >
            提 交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog
      v-model="dialogApp.visible"
      :title="dialogApp.title"
      width="500px"
      @close="handleCloseDialogApp"
    >
      <el-input v-noSpace v-model="approvedRemake" type="textarea" placeholder="请输入审核意见" />

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handlePass('pass')">通 过</el-button>
          <el-button type="primary" @click="handlePass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <!-- <el-dialog
      v-model="dialogDel.visible"
      :title="dialogDel.title"
      width="500px"
      @close="handleCloseDialogDel"
    >
      <p>删除后数据将不可显示，且本条库存数据清空，确认是否继续？</p>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handleDel()">确 定</el-button>
          <el-button @click="dialogDel.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 退货 -->
    <el-dialog
      :title="returnDialog.title"
      width="1000px"
      @close="handleCloseReturnDialog"
      v-model="returnDialog.visible"
    >
      <el-form
        ref="returnDialogFormDataRef"
        :model="returnDialogFormData"
        label-width="120px"
        :rules="returnRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售订单编号" prop="code">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.code"
                placeholder="请选择销售订单编号"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.customerName"
                placeholder="请输入客户名称"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="companyCode">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.companyCode"
                placeholder="请输入客户编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="数量" prop="qty">
              <el-input-number v-model="dialogFormData.qty" placeholder="请输入" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="退货方式" prop="returnMethod">
              <el-select v-model="returnDialogFormData.returnMethod" placeholder="全部" clearable>
                <el-option label="退货退款" :value="'1'" />
                <el-option label="只退货" :value="'2'" />
                <el-option label="报废退货" :value="'3'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="returnDialogFormData.returnMethod !== '2'">
            <el-form-item label="折扣率" prop="discountRate">
              <el-input-number
                v-model="returnDialogFormData.discountRate"
                placeholder="请输入折扣率"
                @change="handleDiscountRateChange"
                :min="0"
                :max="100"
                class="!w-full"
              >
                <template #suffix>%</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-if="returnDialogFormData.returnMethod !== '2'">
            <el-form-item label="折后金额" prop="discountAmount">
              <el-input-number
                v-model="discountAmount"
                placeholder="请输入折后金额"
                :min="0"
                class="!w-full"
                :max="returnDialogFormData.discountAmount"
              >
                <template #suffix>元</template>
              </el-input-number>
            </el-form-item>
          </el-col> -->

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.remark"
                :rows="4"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider />

      <!-- <p>{{ dialog.title == '新增'?'添加产品':'修改产品' }}</p> -->

      <el-form
        ref="returnDialogFormDataProRef"
        :model="returnDialogFormDataPro"
        :rules="rulesPro"
        label-width="120px"
        v-if="returnDialogFormData.returnMethod !== '3'"
      >
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-input v-noSpace
                v-model="dialogFormDataPro.productType"
                placeholder="请输入产品类型"
                disabled
              />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input
                v-noSpace
                v-model="returnDialogFormDataPro.productCode"
                placeholder="请输入产品编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="productCode">
              <el-select
                v-model="returnDialogFormDataPro.productCode"
                placeholder="请选择产品名称"
                clearable
                filterable
                @change="changeReturnProduct"
                @visible-change="searchCode(returnDialogFormData.code)"
              >
                <el-option
                  v-for="item in returnProduct"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`数量（${unitFormat(dialogFormDataPro.unit) || ''}）`" prop="qty">
              <el-input-number
                v-model="productQty"
                :max="returnDialogFormDataPro.qty"
                :min="0"
                placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                v-model="returnDialogFormDataPro.unitPrice"
                disabled
                placeholder="请输入单价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="rowRemark">
              <el-input
                v-noSpace
                v-model="returnDialogFormDataPro.rowRemark"
                :rows="2"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" />
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="handleSavePro('return')">添加退货产品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        v-loading="loading"
        :data="returnProductData"
        :height="tableRowHight"
        v-if="returnDialogFormData.returnMethod !== '3'"
      >
        <!-- <el-table-column label="产品类型" align="center" prop="productType" />
        <el-table-column label="产品编号" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="数量（kg）" align="center" prop="qty" />
        <el-table-column label="单价" align="center" prop="unitPrice" /> -->

        <el-table-column prop="productCode" label="产品编号" align="center" width="110" />
        <el-table-column prop="productName" label="产品名称" align="center" width="110" />
        <!-- <el-table-column prop="discountRate" label="折扣率" align="center" width="110" /> -->
        <!-- 修改 quantity 和 price 列 -->
        <el-table-column label="每份数量" prop="qty" align="center" width="200">
          <template #default="scope">
            <div class="">
              {{ scope.row.qty }}
              {{ unitFormat(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>
        <!-- <template #default="scope">
            <el-input v-noSpace
              v-model="scope.row.quantity"
              @keyup.enter="handleUpdate(scope.row, 'quantity')"
            />
          </template>
        </el-table-column> -->
        <el-table-column label="单价(元)" prop="unitPrice" align="center" width="200" />
        <!-- <template #default="scope">
            <el-input v-noSpace v-model="scope.row.price" @keyup.enter="handleUpdate(scope.row, 'price')" />
          </template>
        </el-table-column> -->
        <el-table-column prop="rowRemark" label="备注" show-overflow-tooltip align="center" />
        <el-table-column label="操作" fixed="right" width="70" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              link
              @click="handleReturnProduct(scope.row, scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <p class="df-fe">总退款金额：￥6700</p> -->
      <template #footer>
        <div v-if="dialog.title = '查看'" class="dialog-footer flex-center">
          <el-button @click="handleCloseReturnDialog">取 消</el-button>
          <!-- <el-button type="primary" @click="handleSubmit('save')">暂 存</el-button> -->
          <el-button v-debounce="handleSubmitReturn" type="primary">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import SalesAPI, {
  SalesPageQuery,
  SalesPageQueryPageVO,
  SalesOrderInfo,
  SalesOrderDetail,
} from "@/api/order/sales";
import { FormItemRule } from "element-plus/es";
import configApi, { ConfigType } from "@/api/config/config";

import organizationalAPI from "@/api/basicData/organizational";
import orderReturnAPI, { orderReturnDetail, orderReturnInfo } from "@/api/orderReturn/orderReturn";
import UserAPI from "@/api/system/user";
import deliveryOrderMaintenanceApi from "@/api/LogisticsManagement/deliveryOrderMaintenance";
import stockOutApi from "@/api/warehouseManage/stockOut";

// 列表高度
const tableHight = `250px`;
// Row列表高度
const tableRowHight = `250px`;

//row列表数据
const rowTableData = ref<SalesOrderDetail[]>([]);

//产品名称
const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const optionsName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const optionsContact = ref<{ value: string; label: string; tel: string }[]>([]); // 显式指定类型

const optionsAddress = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};
const optionsSalesMan = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const formDisabled = ref(false);

//row信息
const rowObj = ref<SalesPageQueryPageVO | null>(null);

//暂存 按钮isShow
const buttonIsishow = ref(false);
//暂存 按钮类型判断新增还是修改
const savebutIsType = ref("");

// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 新增弹窗
const dialogPro = reactive({
  title: "",
  visible: false,
});

//// 审核弹窗
const dialogApp = reactive({
  title: "",
  visible: false,
});

//// 审核弹窗
const dialogDel = reactive({
  title: "",
  visible: false,
});

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const queryParams = reactive<SalesPageQuery>({
  isReturnOrder: 0,
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<SalesPageQueryPageVO[]>();
const total = ref(0);
const loading = ref(false);

// 新增/修改form
const dialogFormData = reactive<SalesOrderInfo>({
  /** 订单编号 */
  code: "",

  /** 订单类型 */
  docType: "",

  /** 客户编号 */
  companyCode: "",

  /** 客户名称 */
  customerName: "",

  /** 联系人 */
  contactPerson: "",

  /** 联系人电话 */
  contactPhone: "",

  /** 归属合同 */
  contractCode: "",

  /** 业务员 */
  salesMan: "",

  /** 状态 */
  status: 0,

  /** 备注 */
  remark: "",

  /** 审核意见 */
  approvalComment: "",

  salesOrderDetailList: [] as SalesOrderDetail[],
  /** 判断是否退货 */
  isReturnOrder: 0,
  /** 客户地址 */
  address: "",
  /** 送货日期 */
  deliveryDate: "",
});

const dialogFormDataRef = ref(ElForm);

// 添加产品
const dialogFormDataPro = reactive<SalesOrderDetail>({
  productType: "",
  productCode: "",
  productName: "",
  qty: 0,
  unitPrice: 0,
  remark: "",
  discountRate: 0,
});

const dialogFormDataProRef = ref();

// 审核意见
const approvedRemake = ref("");

const rules = reactive<Record<string, FormItemRule[]>>({
  docType: [{ required: true, message: "订单类型是必填项", trigger: "blur" }],
  salesMan: [{ required: true, message: "业务员是必填项", trigger: "blur" }],
  deliveryDate: [{ required: true, message: "送货日期是必填项", trigger: "blur" }],
  status: [{ required: true, message: "状态是必填项", trigger: "change" }],
  customerName: [{ required: true, message: "客户名称是必填项", trigger: "blur" }],
  address: [{ required: true, message: "客户地址是必填项", trigger: "blur" }],
});

const rulesPro = reactive<Record<string, FormItemRule[]>>({
  productName: [{ required: true, message: "产品名称是必填项", trigger: "change" }],
  qty: [
    { required: true, message: "数量是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "数量必须是一个数字", trigger: ["blur", "change"] },
    { min: 0, type: "number", message: "数量必须大于等于0", trigger: ["blur", "change"] },
  ],
  unitPrice: [
    { required: true, message: "单价是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "单价必须是一个数字", trigger: ["blur", "change"] },
    { min: 0, type: "number", message: "单价必须大于等于0", trigger: ["blur", "change"] },
  ],
});

// 查询
function handleQuery() {
  loading.value = true;
  buttonIsishow.value = false;
  SalesAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
      rowTableData.value = [];
    })
    .catch((error) => {})
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  rowTableData.value = [];
  handleQuery();
}

//退货
const returnDialogFormDataRef = ref();
const returnDialog = reactive({
  title: "",
  visible: false,
});
const returnDialogFormData = reactive<orderReturnInfo>({
  /** 订单编号 */
  code: "",
  otherRef: "",
  /** 订单类型 */
  docType: "",

  /** 客户编号 */
  companyCode: "",

  /** 客户名称 */
  customerName: "",
  discountRate: 0,
  discountAmount: 0,
  returnMethod: "",
  remark: "",
  contractCode: "",
  salesMan: "",
});
//退货产品
const returnDialogFormDataProRef = ref();
const returnDialogFormDataPro = reactive<orderReturnDetail>({
  productType: "",
  productCode: "",
  productName: "",
  qty: 0,
  unitPrice: 0,
  remark: "",
});
//退货产品列表
const returnProductData = ref<orderReturnDetail[]>([]);

//退货规则
const returnRules = reactive<Record<string, FormItemRule[]>>({
  discountRate: [
    { required: true, message: "折扣率是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "折扣率必须是一个数字", trigger: ["blur", "change"] },
    {
      min: 0,
      max: 100,
      type: "number",
      message: "折扣率必须在0-100之间",
      trigger: ["blur", "change"],
    },
  ],
  returnMethod: [{ required: true, message: "退货方式是必填项", trigger: ["blur", "change"] }],
  discountAmount: [{ required: true, message: "折扣金额是必填项", trigger: ["blur", "change"] }],
});

const changeReturnProduct = (val: any) => {
  const product = returnProduct.value.filter((item) => item.value === val)[0];
  returnDialogFormDataPro.productName = product.label;
  returnDialogFormDataPro.productCode = product.value;
  returnDialogFormDataPro.qty = product.qty;
  productQty.value = product.qty;
  returnDialogFormDataPro.unitPrice = product.unitPrice;
  returnDialogFormDataPro.unit = product.unit;
  returnDialogFormDataPro.discountRate = product.discountRate;
};
const returnProduct = ref<
  {
    value: string;
    label: string;
    qty: number;
    rowRemark: string;
    unitPrice: number;
    unit: string;
    discountRate: number;
  }[]
>([]);
function searchCode(code: any) {
  orderReturnAPI
    .searchCode(code)
    .then((data) => {
      returnProduct.value = (data?.detailList || []).map((item: any) => ({
        value: item.productCode,
        label: item.productName,
        qty: item.qty,
        rowRemark: item.rowRemark,
        unitPrice: item.unitPrice,
        unit: item.unit,
        discountRate: item.discountRate,
      }));
      console.log(options.value, "options.value");
      // rowTableData.value = data?.detailList || [];
      // ElMessage.success(`取消退货成功`);
      // handleQuery();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {});
}

//退货数量
const productQty = ref(0);

const discountAmount = ref(0);
// 修改折扣率
const handleDiscountRateChange = (val: number | undefined) => {
  discountAmount.value = Number(((rowObj.value?.orderAmount || 0) * ((val || 0) / 100)).toFixed(2));
};

//打开退货弹窗
async function handleReturn(row: SalesPageQueryPageVO | null = null) {
  //如果查到退货订单不允许退货
  orderReturnAPI
    .getPage({
      pageSize: 1,
      pageNum: 1,
      otherRef: row?.code,
      isReturnOrder: 1,
      statusList: [0, 1, 2, 3, 4, 5],
    })
    .then((res) => {
      if (res.total == 0) {
        returnDialogFormData.code = row?.code;
        returnDialogFormData.customerName = row?.customerName;
        returnDialogFormData.companyCode = row?.companyCode;
        returnDialogFormData.discountRate = 100;
        returnDialogFormData.discountAmount = row?.discountAmount || 0;
        returnDialogFormData.contractCode = row?.contractCode;
        returnDialogFormData.salesMan = row?.salesMan;
        returnDialogFormData.id = NaN;
        discountAmount.value = row?.orderAmount || 0;
        returnDialog.visible = true;
      } else {
        ElMessage.error(`该订单已在退货列表，请等待审核员审核`);
      }
    });
}
const handleCloseReturnDialog = () => {
  returnDialog.visible = false;
  if (returnDialogFormData.returnMethod !== "3") {
    returnDialogFormDataProRef.value?.resetFields();
    returnDialogFormDataProRef.value?.clearValidate();
  }

  productQty.value = 0;
  returnProductData.value = [];
};
//删除退货产品
const handleReturnProduct = (row: any, index: number) => {
  if (index !== -1) {
    returnProductData.value.splice(index, 1);
    ElMessage.success(`删除成功`);
  }
};

//提交退货
function handleSubmitReturn() {
  returnDialogFormDataRef.value.validate().then((validate: boolean) => {
    if (!validate) return;
    if (returnDialogFormData.returnMethod != "3" && returnProductData.value.length === 0)
      return ElMessage.error(`退货产品不能为空`);
    // returnDialogFormData.discountAmount = discountAmount.value;
    returnDialogFormData.isReturnOrder = 1;

    returnDialogFormData.salesOrderDetailList = returnProductData.value;
    returnDialogFormData.otherRef = returnDialogFormData.code;
    console.log(returnDialogFormData, "returnDialogFormData");

    orderReturnAPI
      .saveOrUpdateTSalesOrder(returnDialogFormData)
      .then((data) => {
        handleCloseReturnDialog();
        //修该订单状态为6
        ElMessage.success(`退货成功`);
      })
      .catch((err) => {})
      .finally(() => {
        handleQuery();
      });
  });
}

// 新增/修改
function handleOpenDialog(row: SalesPageQueryPageVO | null = null, type: string) {
  let upData = {};
  if (type == "view") {
    dialog.visible = true;
    getContacts(row?.companyCode);
    upData = { ...row };
    nextTick(() => {
      Object.assign(dialogFormData, upData);
    });
    dialog.title = "查看";
    handleRowClick(row, {}, null);
    getAddressList();
    buttonIsishow.value = false;
    formDisabled.value = true;
  } else if (type == "add") {
    dialog.visible = true;
    dialog.title = "新增";
    console.log("dialog.title", dialog.title);
    buttonIsishow.value = true; //按钮
    savebutIsType.value = "add"; //暂存类型判断
    formDisabled.value = false;
    rowTableData.value = [];
  } else if (type == "del") {
    upData = { ...row };
    ElMessageBox.confirm(`是否删除该条数据`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      orderReturnAPI
        .delTSalesOrder(row?.id as number)
        .then((data) => {
          ElMessage.success(`删除成功`);
          handleQuery();
        })
        .catch((err) => {})
        .finally(() => {});
    });

    // dialogDel.title = "删除";
    // dialogDel.visible = true;
  } else {
    dialog.visible = true;
    getContacts(row?.companyCode);

    upData = { ...row };
    nextTick(() => {
      Object.assign(dialogFormData, upData);
    });
    rowObj.value = { ...row };
    if (rowObj.value) {
      handleRowClick(row, {}, null);
      getAddressList();
    }
    dialog.title = "修改";
    buttonIsishow.value = true;
    savebutIsType.value = "edit"; //暂存类型判断
    console.log("dialogFormDataedit：", dialogFormData);
    formDisabled.value = false;
  }
}

//审核
function handleApproved(row: SalesPageQueryPageVO | null = null) {
  if (row) {
    rowObj.value = { ...row };
    dialogApp.visible = true;
    dialogApp.title = "审核意见";
    approvedRemake.value = row?.approvalComment || ""; // 使用可选链操作符并提供默认值
  } else {
    console.warn("handleApproved函数被调用时，row参数为null。");
  }
}

// 新增的方法：处理行点击事件
function handleRowClick(row: any, column: any, event: MouseEvent | null) {
  console.log("row", row);
  rowObj.value = { ...row };
  buttonIsishow.value = true;
  SalesAPI.getTSalesOrderDetailByCode(row.code)
    .then((data) => {
      rowTableData.value = data?.detailList;
      // ElMessage.success(`保存成功`);
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dialogFormDataRef.value?.clearValidate();
  dialogFormDataRef.value?.resetFields();

  approvedRemake.value = "";
  clearDialogFormDataPro();

  rowTableData.value = []; // 清空表格数据
  optionsContact.value = []; // 清空联系人数据

  clearDialogFormData();
}

function handleSavePro(type: string) {
  if (type == "return") {
    returnDialogFormDataProRef.value.validate((valid: boolean) => {
      if (!valid) {
        return;
      }
      // 检查是否已经存在相同的 productName
      const isDuplicate = returnProductData.value.some(
        (item) => item.productCode === returnDialogFormDataPro.productCode
      );
      if (isDuplicate) {
        ElMessage.error("该产品名称已存在，请勿重复添加");
        return;
      }
      returnProductData.value?.push({
        productType: returnDialogFormDataPro.productType,
        productCode: returnDialogFormDataPro.productCode,
        productName: returnDialogFormDataPro.productName,
        qty: productQty.value,
        unitPrice: returnDialogFormDataPro.unitPrice,
        rowRemark: returnDialogFormDataPro.remark,
        unit: returnDialogFormDataPro.unit,
        discountRate: returnDialogFormDataPro.discountRate,
      });
      ElMessage.success("添加成功");
      returnDialogFormDataProRef.value.resetFields();
      productQty.value = 0;
    });
    return;
  }

  dialogFormDataProRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    // 检查是否已经存在相同的 productName
    const isDuplicate = rowTableData.value.some(
      (item) => item.productName === dialogFormDataPro.productName
    );
    if (isDuplicate) {
      ElMessage.error("该产品名称已存在，请勿重复添加");
      return;
    }
    rowTableData.value?.push({
      productType: dialogFormDataPro.productType,
      productCode: dialogFormDataPro.productCode,
      productName: dialogFormDataPro.productName,
      qty: dialogFormDataPro.qty,
      unitPrice: dialogFormDataPro.unitPrice,
      rowRemark: dialogFormDataPro.remark,
      unit: unitValue.value.value,
      discountRate: dialogFormDataPro.discountRate,
    });
    ElMessage.success("添加成功");
    clearDialogFormDataPro();
  });
}

//是否通过
function handlePass(type: string) {
  const status = type === "pass" ? 2 : 1;
  //打印当前产品

  console.log(rowTableData.value, "rowTableData");

  SalesAPI.editTSalesOrder({
    id: rowObj.value?.id,
    status: status,
    approvalComment: approvedRemake.value,
  })
    .then((data) => {
      //如果是紧急订单新增送货单和出库单
      if (type == "pass") {
        if (rowObj.value?.docType == "1") {
          deliveryOrderMaintenanceApi
            .saveOrUpdateDeliveryOrder({
              sourceCode: rowObj.value?.code,
              refCode: rowObj.value?.code,
              salesOrderCodes: rowObj.value?.code,
              status: 1,
            })
            .then(() => {
              SalesAPI.getTSalesOrderDetailByCode(rowObj.value?.code || "").then((data) => {
                let productList = data?.detailList?.map((item: any) => {
                  return {
                    amount: item.qty * item.unitPrice,
                    iocode: "o",
                    productCode: item.productCode,
                    productCodeName: item.productCodeName,
                    qty: item.qty,
                    unit: item.unit,
                    unitPrice: item.unitPrice,
                  };
                });

                stockOutApi.addTopStore({
                  sourceCategory: 5,
                  sourceCode: rowObj.value?.code,
                  reason: 6,
                  iocode: "o",
                  stockTranDetailList: productList,
                });
              });
            });
        } else {
          //新增出库单
          SalesAPI.getTSalesOrderDetailByCode(rowObj.value?.code || "").then((data) => {
            let productList = data?.detailList?.map((item: any) => {
              return {
                amount: item.qty * item.unitPrice,
                iocode: "o",
                productCode: item.productCode,
                productCodeName: item.productCodeName,
                qty: item.qty,
                unit: item.unit,
                unitPrice: item.unitPrice,
              };
            });
            stockOutApi.addTopStore({
              sourceCategory: 5,
              sourceCode: rowObj.value?.code,
              reason: 6,
              iocode: "o",
              stockTranDetailList: productList,
            });
          });
        }
      } else {
      }
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {
      ElMessage.success(`操作成功`);
      handleQuery();
      dialogApp.visible = false;
      approvedRemake.value = "";
      loading.value = false;
    });
}

function handleDel() {
  SalesAPI.rowDel({ id: dialogFormData?.id })
    .then((data) => {
      ElMessage.success(`操作成功`);
      handleQuery();
      dialogDel.visible = false;
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
}

function handleCloseDialogPro() {
  dialogPro.visible = false;
}

function handleCloseDialogApp() {
  approvedRemake.value = "";
  dialogApp.visible = false;
}

function handleCloseDialogDel() {
  dialogDel.visible = false;
}

function clearDialogFormDataPro() {
  let data = {
    qty: 0,
    unitPrice: 0,
    productCode: "",
    productType: "",
    productName: "",
    remark: "",
  };
  Object.assign(dialogFormDataPro, { ...data });
  dialogFormDataProRef.value?.clearValidate();
  dialogFormDataProRef.value?.resetFields();
}

function clearDialogFormData() {
  let data = {
    id: undefined,
    /** 订单编号 */
    code: "",

    /** 订单类型 */
    docType: "",

    /** 客户编号 */
    companyCode: "",

    /** 客户名称 */
    customerName: "",

    /** 联系人 */
    contactPerson: "",

    /** 联系人电话 */
    contactPhone: "",

    /** 归属合同 */
    contractCode: "",

    /** 业务员 */
    salesMan: "",

    /** 状态 */
    status: 0,

    /** 备注 */
    remark: "",

    /** 审核意见 */
    approvalComment: "",

    address: "",
    /** 送货日期 */
    deliveryDate: "",
  };
  Object.assign(dialogFormData, { ...data });
  if (dialogFormDataRef.value) {
    dialogFormDataRef.value?.clearValidate();
    dialogFormDataRef.value?.resetFields();
  }
}
// 提交用户表单（防抖）
// const handleSubmit = useDebounceFn(() => {
//   userFormRef.value.validate((valid: boolean) => {
//     if (valid) {
//       const userId = formData.id;
//       loading.value = true;
//       if (userId) {
//         ManageAPI.update(userId, formData)
//           .then(() => {
//             ElMessage.success("修改用户成功");
//             handleCloseDialog();
//             handleResetQuery();
//           })
//           .finally(() => (loading.value = false));
//       } else {
//         ManageAPI.add(formData)
//           .then(() => {
//             ElMessage.success("新增用户成功");
//             handleCloseDialog();
//             handleResetQuery();
//           })
//           .finally(() => (loading.value = false));
//       }
//     }
//   });
// }, 1000);

// 新增提交
function handleSubmit() {
  dialogFormDataRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    if (!rowTableData?.value?.length) return ElMessage.error("请添加产品列表");
    dialogFormData.salesOrderDetailList = rowTableData.value;
    if (dialog.title == "新增") {
      dialogFormData.salesOrderDetailList = dialogFormData.salesOrderDetailList.map((item) => {
        const { id, ...rest } = item; // 使用对象解构去掉 id 属性
        return rest;
      });
    }
    console.log(dialogFormData.salesOrderDetailList, "dialogFormData.salesOrderDetailList");
    let paramData = <SalesOrderInfo>{};
    if (dialog.title == "新增") {
      paramData.customerName = dialogFormData.customerName;
      paramData.companyCode = dialogFormData.companyCode;
      paramData.contactPerson = dialogFormData.contactPerson;
      paramData.contactPhone = dialogFormData.contactPhone;
      paramData.contractCode = dialogFormData.contractCode;
      paramData.salesMan = dialogFormData.salesMan;
      paramData.remark = dialogFormData.remark;
      paramData.approvalComment = dialogFormData.approvalComment;
      paramData.salesOrderDetailList = dialogFormData.salesOrderDetailList;
      paramData.address = dialogFormData.address;
      paramData.deliveryDate = dialogFormData.deliveryDate;
      paramData.shipCode = dialogFormData.address; // 送货地址
      paramData.status = 0;
      paramData.docType = dialogFormData.docType; // 临时订单
    } else {
      paramData = { ...dialogFormData };
    }
    paramData.isReturnOrder = 0;
    SalesAPI.saveOrUpdateTSalesOrder(paramData)
      .then((data) => {
        ElMessage.success(`操作成功`);
        handleQuery();
        handleCloseDialog();
        clearDialogFormData();
        if (rowObj.value) {
          handleRowClick(rowObj.value, {}, null);
        }
      })
      .catch((error) => {
        // //ElMessage.error(`${error}`); //注释报错弹窗
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

const docTypes = ref([
  {
    value: 0,
    label: "周期订单",
  },
  {
    value: 1,
    label: "紧急订单",
  },
]);

function getDocTypeLabel(status: number) {
  return docTypes.value.find((item) => item.value === status)?.label || "未知状态";
}

const getName = () => {
  SalesAPI.getcusName({ pageNum: 1, pageSize: 999, isVendor: 0, status: 1, isDelete: 0 })
    .then((data) => {
      optionsName.value = (data?.list || []).map((item: any) => ({
        value: item.companyCode,
        label: item.companyName,
        contractCode: item.code,
        contactPerson: item.contactPerson,
        contactPhone: item.contactInfo,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

const getAddressList = () => {
  SalesAPI.getListAddress({ pageNum: 1, pageSize: 20, parentCode: dialogFormData.companyCode })
    .then((data) => {
      console.log(data, "data");

      optionsAddress.value = (data || []).map((item: any) => ({
        value: item.code,
        label: item.address,
        isDefault: item.isDefault,
      }));
      // 使用 find 方法查找默认地址并赋值
      // const defaultAddress = optionsAddress.value.find((item: any) => item.isDefault);
      // if (defaultAddress) {
      //   dialogFormData.address = defaultAddress.value;
      // }
    })
    .catch((error) => {})
    .finally(() => {});
};

const getContacts = (code: any) => {
  SalesAPI.getContacts({ pageNum: 1, pageSize: 999, parentCode: code })
    .then((data) => {
      optionsContact.value = (data || []).map((item: any) => ({
        value: item.id.toString(),
        label: item.contactPerson,
        tel: item.tel,
      }));
    })
    .finally(() => {});
};

const getContractList = () => {
  configApi
    .getProductList({
      pageNum: 1,
      pageSize: 999,
      contractCode: dialogFormData.contractCode,
      productType: "1",
    })
    .then((data) => {
      // rowTableData.value = data?.list || [];
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
        // quantity: item.quantity,
        remark: item.remark,
        price: item.price ? item.price : item.salesPrice,
        unit: item.unit,
      }));
    })
    .catch((error) => {})
    .finally(() => {});
};
const getSalesMan = () => {
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    optionsSalesMan.value = data.list.map((item: any) => ({
      value: item.id.toString(),
      label: item.name,
    }));
    console.log(data, "data");
  });
};
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
const unitFormat = (unit: any) => {
  let unitLabel = unitOptions.value.find((item) => item.value === unit)?.label;
  return unitLabel;
};
function changeProduct(val: any) {
  console.log(val);
  dialogFormDataPro.productCode = val.value;
  dialogFormDataPro.productName = val.label;
  dialogFormDataPro.unitPrice = val.price;
  dialogFormDataPro.remark = val.remark;
  unitValue.value = unitOptions.value.find((item) => item.value === val.unit) as any;
}

function changeName(val: any) {
  dialogFormData.customerName = val.label;
  dialogFormData.companyCode = val.value;
  if (dialogFormData.companyCode) {
    getAddressList();
    getContacts(dialogFormData.companyCode);
  }
  console.log("dialogFormData.companyCode", dialogFormData.companyCode);
  // dialogFormData.contactPerson = val.contactPerson;
  // dialogFormData.contactPhone = val.contactPhone;
  dialogFormData.contractCode = val.contractCode;
  if (dialogFormData.contractCode) {
    getContractList();
  }
}

function changeContactPerson(val: any) {
  console.log("changeContactPerson", val);
  const res = optionsContact.value.filter((ele) => {
    return ele.value === val;
  });
  dialogFormData.contactPerson = res[0].value;
  dialogFormData.contactPhone = res[0].tel;
}

function changeSalesMan(val: any) {
  dialogFormData.salesMan = val.label;
}

// 删除行的方法
function delRow(row: SalesOrderDetail) {
  console.log(row, "rowTableData.value", rowTableData.value);

  const index = rowTableData.value.findIndex((item) => item.productCode === row.productCode);

  if (index !== -1) {
    rowTableData.value.splice(index, 1);
    ElMessage.success("删除成功");
  } else {
    ElMessage.error("删除失败，未找到对应行");
  }
}

function handleUpdate(row: any, type: any) {}
onMounted(() => {
  handleQuery();
  getUnitList();
  getSalesMan();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
